import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { workerApi } from '@renderer/api/worker'
import { ElMessage } from 'element-plus'

// 打手状态枚举
export enum WorkerStatus {
  IDLE = 'idle',       // 空闲
  WORKING = 'working', // 工作中
  REST = 'rest',       // 休息
  OFFLINE = 'offline'  // 离线
}

// 打手信息接口（根据后端DTO调整）
export interface Worker {
  id: number
  workerCode?: string
  nickname: string
  realName?: string
  phone: string
  gender?: string
  age?: number
  avatar?: string
  status: WorkerStatus
  accountStatus?: string
  level?: string
  skillTags?: string // JSON字符串
  skills?: string[] // 前端解析后的技能数组
  commissionRate?: number
  totalOrders?: number
  totalIncome?: number
  averageRating?: number
  lastActiveTime?: string
  joinDate: string
  // 前端计算的字段
  monthlyOrders?: number
  monthlyIncome?: number
  rating?: number
  currentOrder?: string
}

// 打手统计信息接口（根据后端DTO调整）
export interface WorkerStats {
  totalWorkers: number
  onlineWorkers: number
  offlineWorkers: number
  idleWorkers: number
  workingWorkers: number
  onlineRate?: number
  averageRating?: number
  todayActiveWorkers: number
  monthlyNewWorkers: number
}

// 分页参数接口（根据后端API调整）
export interface WorkerQueryParams {
  page: number
  size: number // 后端使用size而不是pageSize
  keyword?: string // 后端使用keyword而不是searchQuery
  status?: string
  accountStatus?: string
  level?: string
  skillTags?: string
  joinDateStart?: string
  joinDateEnd?: string
  ratingRange?: string
  sortBy?: string
  sortOrder?: string
}

// 分页响应接口
export interface WorkerListResponse {
  workers: Worker[]
  total: number
  page: number
  pageSize: number
}

export const useWorkerStore = defineStore('worker', () => {
  // 状态
  const workersList = ref<Worker[]>([])
  const workerStats = ref<WorkerStats>({
    totalWorkers: 0,
    onlineWorkers: 0,
    offlineWorkers: 0,
    idleWorkers: 0,
    workingWorkers: 0,
    todayActiveWorkers: 0,
    monthlyNewWorkers: 0
  })
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(12)
  const total = ref(0)
  const searchQuery = ref('')
  const statusFilter = ref<WorkerStatus | ''>('')


  // 解析技能标签
  const parseSkillTags = (skillTags?: string): string[] => {
    if (!skillTags) return []
    try {
      return JSON.parse(skillTags)
    } catch {
      return []
    }
  }

  // 处理后端返回的打手数据
  const processWorkerData = (worker: any): Worker => {
    return {
      ...worker,
      skills: parseSkillTags(worker.skillTags),
      // 设置默认值
      monthlyOrders: worker.totalOrders || 0,
      monthlyIncome: worker.totalIncome || 0,
      rating: worker.averageRating || 0
    }
  }

  // 计算属性
  const filteredWorkers = computed(() => {
    let filtered = workersList.value

    // 客户端搜索过滤（如果需要）
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filtered = filtered.filter(worker => 
        (worker.nickname?.toLowerCase().includes(query) || 
         worker.realName?.toLowerCase().includes(query) ||
         worker.phone?.includes(query)) ?? false
      )
    }

    // 客户端状态过滤（如果需要）
    if (statusFilter.value) {
      filtered = filtered.filter(worker => worker.status === statusFilter.value)
    }

    return filtered
  })

  const onlineWorkers = computed(() => 
    workersList.value.filter(worker => worker.status === WorkerStatus.IDLE || worker.status === WorkerStatus.WORKING)
  )

  const workingWorkers = computed(() => 
    workersList.value.filter(worker => worker.status === WorkerStatus.WORKING)
  )

  // Actions
  
  /**
   * 获取打手统计数据
   */
  const fetchWorkerStats = async () => {
    try {
      loading.value = true
      const response = await workerApi.getWorkerStats()
      workerStats.value = response.data
      return response
    } catch (error) {
      console.error('获取打手统计失败:', error)
      ElMessage.error('获取统计数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取打手列表
   */
  const fetchWorkerList = async (params?: Partial<WorkerQueryParams>) => {
    try {
      loading.value = true
      const queryParams: WorkerQueryParams = {
        page: currentPage.value,
        size: pageSize.value,
        keyword: searchQuery.value || undefined,
        status: statusFilter.value || undefined,
        ...params
      }

      const response = await workerApi.getWorkerList(queryParams)
      
      // 处理返回的数据
      const processedWorkers = response.data.records.map(processWorkerData)
      workersList.value = processedWorkers
      total.value = response.data.total
      currentPage.value = response.data.current
      
      return response
    } catch (error) {
      console.error('获取打手列表失败:', error)
      ElMessage.error('获取打手列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取单个打手详情
   */
  const fetchWorkerDetail = async (workerId: number) => {
    try {
      const response = await workerApi.getWorkerDetail(workerId)
      
      // 更新本地列表中的打手信息
      const index = workersList.value.findIndex(worker => worker.id === workerId)
      if (index !== -1) {
        workersList.value[index] = response.data
      }
      
      return response
    } catch (error) {
      console.error('获取打手详情失败:', error)
      ElMessage.error('获取打手详情失败')
      throw error
    }
  }

  /**
   * 添加新打手
   */
  const addWorker = async (workerData: Omit<Worker, 'id'>) => {
    try {
      loading.value = true
      const response = await workerApi.createWorker(workerData)
      
      // 添加到本地列表
      workersList.value.unshift(response.data)
      total.value += 1
      
      ElMessage.success('添加打手成功')
      return response
    } catch (error) {
      console.error('添加打手失败:', error)
      ElMessage.error('添加打手失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新打手信息
   */
  const updateWorker = async (workerId: number, workerData: Partial<Worker>) => {
    try {
      loading.value = true
      const response = await workerApi.updateWorker(workerId, workerData)
      
      // 更新本地列表
      const index = workersList.value.findIndex(worker => worker.id === workerId)
      if (index !== -1) {
        workersList.value[index] = { ...workersList.value[index], ...response.data }
      }
      
      ElMessage.success('更新打手信息成功')
      return response
    } catch (error) {
      console.error('更新打手信息失败:', error)
      ElMessage.error('更新打手信息失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新打手状态
   */
  const updateWorkerStatus = async (workerId: number, status: WorkerStatus) => {
    try {
      const response = await workerApi.updateWorkerStatus(workerId, status)
      
      // 更新本地状态
      const worker = workersList.value.find(w => w.id === workerId)
      if (worker) {
        worker.status = status
        worker.lastActiveTime = new Date().toISOString()
      }
      
      // 更新统计数据
      await fetchWorkerStats()
      
      ElMessage.success('状态更新成功')
      return response
    } catch (error) {
      console.error('更新打手状态失败:', error)
      ElMessage.error('状态更新失败')
      throw error
    }
  }

  /**
   * 删除打手
   */
  const deleteWorker = async (workerId: number) => {
    try {
      loading.value = true
      await workerApi.deleteWorker(workerId)
      
      // 从本地列表移除
      const index = workersList.value.findIndex(worker => worker.id === workerId)
      if (index !== -1) {
        workersList.value.splice(index, 1)
        total.value -= 1
      }
      
      ElMessage.success('删除打手成功')
    } catch (error) {
      console.error('删除打手失败:', error)
      ElMessage.error('删除打手失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 为打手分配订单
   */
  const assignOrderToWorker = async (workerId: number, orderId: number) => {
    try {
      const response = await workerApi.assignOrder(workerId, orderId)
      
      // 更新打手状态为工作中
      await updateWorkerStatus(workerId, WorkerStatus.WORKING)
      
      ElMessage.success('订单分配成功')
      return response
    } catch (error) {
      console.error('分配订单失败:', error)
      ElMessage.error('分配订单失败')
      throw error
    }
  }

  /**
   * 获取打手历史记录
   */
  const fetchWorkerHistory = async (workerId: number, params?: any) => {
    try {
      const response = await workerApi.getWorkerHistory(workerId, params)
      return response
    } catch (error) {
      console.error('获取打手历史记录失败:', error)
      ElMessage.error('获取历史记录失败')
      throw error
    }
  }

  /**
   * 获取打手业绩报表
   */
  const fetchWorkerPerformance = async (workerId: number, params?: any) => {
    try {
      const response = await workerApi.getWorkerPerformance(workerId, params)
      return response
    } catch (error) {
      console.error('获取打手业绩失败:', error)
      ElMessage.error('获取业绩数据失败')
      throw error
    }
  }

  /**
   * 重置筛选条件
   */
  const resetFilters = () => {
    searchQuery.value = ''
    statusFilter.value = ''
    currentPage.value = 1
  }

  /**
   * 设置搜索条件
   */
  const setSearchQuery = (query: string) => {
    searchQuery.value = query
    currentPage.value = 1
  }

  /**
   * 设置状态筛选
   */
  const setStatusFilter = (status: WorkerStatus | '') => {
    statusFilter.value = status
    currentPage.value = 1
  }

  /**
   * 设置分页
   */
  const setPagination = (page: number, size: number) => {
    currentPage.value = page
    pageSize.value = size
  }

  /**
   * 刷新数据
   */
  const refreshData = async () => {
    await Promise.all([
      fetchWorkerStats(),
      fetchWorkerList()
    ])
  }

  return {
    // 状态
    workersList,
    workerStats,
    loading,
    currentPage,
    pageSize,
    total,
    searchQuery,
    statusFilter,
    
    // 计算属性
    filteredWorkers,
    onlineWorkers,
    workingWorkers,
    
    // Actions
    fetchWorkerStats,
    fetchWorkerList,
    fetchWorkerDetail,
    addWorker,
    updateWorker,
    updateWorkerStatus,
    deleteWorker,
    assignOrderToWorker,
    fetchWorkerHistory,
    fetchWorkerPerformance,
    resetFilters,
    setSearchQuery,
    setStatusFilter,
    setPagination,
    refreshData
  }
})